#!/bin/bash

# 四维量子引擎 - 一键启动脚本

echo ""
echo "╔═══════════════════════════════════════════════════════════╗"
echo "║                                                           ║"
echo "║     🌟 四维一体量子法则AI系统 🌟                         ║"
echo "║     Four-Dimensional Quantum Law AI System                ║"
echo "║                                                           ║"
echo "║     LAW-SEED-0721 | 量子编码启动中...                     ║"
echo "║                                                           ║"
echo "╚═══════════════════════════════════════════════════════════╝"
echo ""

# 检查Go环境
echo "🔍 检查Go环境..."
if ! command -v go &> /dev/null; then
    echo "❌ 错误: 未找到Go环境"
    echo "   请安装 Go 1.21+ : https://golang.org/dl/"
    exit 1
fi

GO_VERSION=$(go version | awk '{print $3}')
echo "✅ Go环境检测成功: $GO_VERSION"
echo ""

# 下载依赖
echo "📦 下载依赖包..."
go mod download
if [ $? -ne 0 ]; then
    echo "❌ 依赖下载失败"
    exit 1
fi

go mod tidy
echo "✅ 依赖准备完成"
echo ""

# 检查端口
PORT=${PORT:-8080}
echo "🔌 检查端口 $PORT..."
if lsof -Pi :$PORT -sTCP:LISTEN -t >/dev/null 2>&1 ; then
    echo "⚠️  警告: 端口 $PORT 已被占用"
    echo "   请设置其他端口: export PORT=8090"
    read -p "   是否继续? (y/n) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

# 创建必要的目录
echo "📁 创建必要目录..."
mkdir -p bin logs data

# 设置默认环境变量
export QUANTUM_QUBITS=${QUANTUM_QUBITS:-4}
export PORT=${PORT:-8080}

echo "✅ 环境配置完成"
echo ""

# 显示配置信息
echo "⚙️  当前配置:"
echo "   - 量子比特数: $QUANTUM_QUBITS"
echo "   - 服务端口: $PORT"
echo "   - 工作目录: $(pwd)"
echo ""

# 启动服务
echo "🚀 启动量子引擎服务器..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

go run cmd/quantum-server/main.go

# 如果服务异常退出
if [ $? -ne 0 ]; then
    echo ""
    echo "❌ 服务启动失败"
    echo ""
    echo "📝 故障排查建议:"
    echo "   1. 检查 Go 版本是否 >= 1.21"
    echo "   2. 运行 'go mod tidy' 修复依赖"
    echo "   3. 检查端口是否被占用"
    echo "   4. 查看错误日志定位问题"
    echo ""
    exit 1
fi
